package com.project.nimsen.web.sys;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.project.nimsen.dto.WxinfoDto;
import com.project.nimsen.dto.WxsendmsgDto;
import com.project.nimsen.entity.Site;
import com.project.nimsen.entity.User;
import com.project.nimsen.entity.Wxinfo;
import com.project.nimsen.entity.Wxsendmsg;
import com.project.nimsen.service.IWxinfoService;
import com.project.nimsen.service.IWxsendmsgService;
import com.project.nimsen.util.WebUtil;
import com.project.nimsen.weixin.common.WeiXinConstant;
import com.project.jdbc.utils.DateUtils;
import com.project.jdbc.utils.Page;
import com.project.jdbc.web.BaseMVCAction;
/**
 * 用户Control
 * */
@Controller
@RequestMapping(value ="/sys/weixin")
public class WeiXinInfoControl extends BaseMVCAction {
	@Resource
	WebUtil webUtil;
	@Resource
	IWxinfoService wxinfoService;
	@Resource
	IWxsendmsgService wxsendmsgService;
	/**
	 * 跳转微信设置页面
	 * */
	@RequestMapping(value ="/info")
	public String info(HttpServletRequest request){
		return "/WEB-INF/sys/weixin/info";
	}
	/**
	 * 得到当前微信的url信息
	 * */
	@RequestMapping(value ="/wxurl")
	public void wxurl(HttpServletRequest request, HttpServletResponse response){
		try {
			response.getWriter().println(webUtil.wxurl(request));
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
	}
	/**
	 * 得到当前微信信息
	 * */
	@RequestMapping(value ="/wxinfo")
	@ResponseBody
	public Wxinfo wxinfo(HttpServletRequest request){
		Wxinfo wxinfo = null;
		try {
			Site site = webUtil.currSite(request);
			wxinfo = wxinfoService.findBysid(site.getId());
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return wxinfo;
	}
	/**
	 * 查询默认回复的关键字
	 * */
	@RequestMapping(value ="/defaultRmsg")
	@ResponseBody
	public Wxsendmsg defaultRmsg(HttpServletRequest request){
		Wxsendmsg targetmsg = null;
		try {
			Site site = webUtil.currSite(request);
			Wxsendmsg defaultmsg = wxsendmsgService.findByKeyWord(WeiXinConstant.WEIXIN_MSGTYPE_DEFAULT, site.getId());
			if(defaultmsg==null)
				return null;
			targetmsg = wxsendmsgService.findByid(defaultmsg.getTargetid());
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return targetmsg;
	}
	/**
	 * 得到当前token信息
	 * */
	@RequestMapping(value ="/wxtoken")
	public void wxtoken(HttpServletRequest request, HttpServletResponse response){
		try {
			response.getWriter().println(webUtil.wx_token(request));
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
	}
	/**
	 * 保存一个微信公众号信息
	 * */
	@RequestMapping(value ="/add")
	public void add(HttpServletRequest request,HttpServletResponse response){
		try {
			User use = webUtil.getCurrUser();//当前登录人
			Wxinfo wxinfo = null;
			String id = getParameter("id");
			if(StringUtils.isNotBlank(id)){
				wxinfo = wxinfoService.findByid(id);
			}else{
				wxinfo = new Wxinfo();
				wxinfo.setActive(0);;
				wxinfo.setCreateTime(new Date());
				wxinfo.setCreateUser(use.getId());
			}
			
			Site site = webUtil.currSite(request);
			wxinfo.setSiteid(site.getId());
			wxinfo.setAppid(getParameter("appid"));
			wxinfo.setAppsecret(getParameter("appsecret"));
			wxinfo.setWeixinumber(getParameter("weixinumber"));
			wxinfo.setWxoldid(getParameter("wxoldid"));
			wxinfo.setWxusername(getParameter("wxusername"));
			
			WxinfoDto dto = new WxinfoDto();
			dto.setInfo(wxinfo);
			dto.setDefaultkeword(getParameter("defaultkeword"));

			response.getWriter().println(wxinfoService.saveByDto(dto));
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
	}
	
	
	//以下为文本回复处理信息
	
	/**
	 * 跳转到文本回复页面
	 * */
	@RequestMapping(value ="/textr")
	public String text(HttpServletRequest request){
		return "/WEB-INF/sys/weixin/textr";
	}
	@RequestMapping(value="/search_text")
	@ResponseBody
	public Map<String, Object> searchtext(HttpServletRequest request,HttpServletResponse response){
		//返回JSON信息
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			map = search(request, WeiXinConstant.WEIXIN_MSGTYPE_TEXT);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return map;
	}
	/**
	 * 查询方法
	 * */
	private Map<String, Object> search(HttpServletRequest request, String wx_mstType_text)throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		//分页信息
		Page page = new Page(getIntegerParameter("page"));
		page.setPageSize(getIntegerParameter("rows"));
		map.put("total", 0);
		WxsendmsgDto dto = new WxsendmsgDto();
		dto.setPage(page);
		dto.setRtype(wx_mstType_text);
		//站点信息
		Site site = webUtil.currSite(request);
		dto.setSiteid(site.getId());
		List<Map<String, Object>> rows = wxsendmsgService.findByDto(dto);
		if(CollectionUtils.isEmpty(rows)){
			map.put("rows", "");
			return map;
		}
		//转换时间
		for(Map<String, Object> row : rows){
			row.put("matchtype", "完全匹配");
			Date createTime = (Date)row.get("createTime");
			row.put("createTime", DateUtils.convertDate2String(createTime));
		}
		map.put("rows", rows);
		map.put("total", page.getTotalCount());
		return map;
	}
	/**
	 * 得到一个文本回复信息
	 * */
	@RequestMapping(value="text")
	@ResponseBody
	public Wxsendmsg text(HttpServletRequest request, HttpServletResponse response){
		try {
			Wxsendmsg msg = wxsendmsgService.findByid(getParameter("id"));
			return msg;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return null;
	}
	/**
	 * 验证触发关键字是否重复
	 * */
	@RequestMapping(value="validate")
	@ResponseBody
	public Map<String,Object> validate(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> map = new HashMap<String,Object>();
		WxsendmsgDto dto = new WxsendmsgDto();
		dto.setValifield("keyword");
		dto.setValivalue(getParameter("keyword"));
		dto.setId(getParameter("id"));
		try {
			Site site = webUtil.currSite(request);
			dto.setSiteid(site.getId());
			Map<String, Object> model = wxsendmsgService.findValidate(dto);
			if(model!=null){
				map.put("success", false);
				map.put("message", "系统中已经存在关键字为"+dto.getValivalue()+"的回复内容!");
			}else{
				map.put("success", true);
				map.put("message", "");
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return map;
	}
	/**
	 * 文本回复保存
	 * */
	@RequestMapping(value="txt_add")
	public void txt_add(HttpServletRequest request,HttpServletResponse response){
		String id = getParameter("id");
		Wxsendmsg msg = null;
		try {
			if(StringUtils.isNotBlank(id))
				msg = wxsendmsgService.findByid(id);
			else{
				msg = new Wxsendmsg();
				msg.setActive(0);
				msg.setCreateTime(new Date());
				//当前登录人信息
				User use = webUtil.getCurrUser();
				msg.setCreateUser(use.getId());
				msg.setMsgtype(WeiXinConstant.WEIXIN_MSGTYPE_TEXT);
				//所属站点信息
				Site site = webUtil.currSite(request);
				msg.setSiteid(site.getId());
			}
			msg.setKeyword(getParameter("keyword"));
			msg.setRtext(getParameter("rtext"));
			
			//保存信息
			if(StringUtils.isNotBlank(id)){
				Integer re = wxsendmsgService.update(msg);
				response.getWriter().println(re);
				return;
			}else{
				Object obj = wxsendmsgService.save(msg);
				response.getWriter().println(obj);
				return;
			}
//			response.getWriter().println(true);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			try {
				response.getWriter().println(e);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
	/**
	 * 删除一个回复信息
	 * */
	@RequestMapping(value="delete")
	@ResponseBody
	public Map<String, Object> delete(HttpServletRequest rquest,HttpServletResponse response){
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			boolean result =  wxsendmsgService.deleteByid(getParameter("id"));
			if(!result){
				map.put("success", false);
				map.put("message", "删除失败！");
				return map;
			}
			map.put("success", true);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return map;
	}
	/**
	 * 图文回复
	 * */
	@RequestMapping(value="newsr")
	public String newsr(HttpServletRequest request, HttpServletResponse response){
		return "/WEB-INF/sys/weixin/newsr";
	}
	@RequestMapping(value="news_add")
	public void news_add(HttpServletRequest request,HttpServletResponse response){
		String id = getParameter("id");
		WxsendmsgDto dto = new WxsendmsgDto();
		Date nowDate = new Date();
		//当前登录人信息
		User use = webUtil.getCurrUser();
		try{
			Wxsendmsg msg = null;
			//所属站点信息
			Site site = webUtil.currSite(request);
			if(StringUtils.isNotBlank(id)){
				msg = wxsendmsgService.findByid(id);
			}else{
				msg = new Wxsendmsg();
				msg.setActive(0);
				msg.setCreateTime(nowDate);
				msg.setCreateUser(use.getId());
				msg.setSiteid(site.getId());
				msg.setMsgtype(WeiXinConstant.WEIXIN_MSGTYPE_NEWS);
			}
			msg.setKeyword(getParameter("keyword"));
			dto.setNewsr(msg);
			
			//子信息
			String[] titles = request.getParameterValues("title");
			String[] urls = request.getParameterValues("url");
			String[] fileids = request.getParameterValues("fileid");
			String[] rtexts = request.getParameterValues("rtext");
			
			int childs_count = titles.length;
			for(int i=0;i<childs_count;i++){
				Wxsendmsg child = new Wxsendmsg();
				
				child.setActive(0);
				child.setCreateTime(new Date());
				child.setCreateUser(use.getId());
				child.setSiteid(site.getId());
				child.setMsgtype(WeiXinConstant.WEIXIN_MSGTYPE_NEWS);
				child.setTitle(titles[i]);
				child.setUrl(urls[i]);
				child.setFileid(fileids[i]);
				child.setRtext(rtexts[i]);
				child.setSort(i+1);
				
				dto.addChild(child);
			}
			wxsendmsgService.saveNews(dto);
			JSONObject json = new JSONObject();
			json.put("error", 0);
			response.getWriter().println(json.toString());
		}catch(Exception e){
			logger.error(e);
			e.printStackTrace();
		}
	}
	/**
	 * 图文查询
	 * */
	@RequestMapping(value="/search_news")
	@ResponseBody
	public Map<String, Object> searchnews(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map = search(request, WeiXinConstant.WEIXIN_MSGTYPE_NEWS);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return map;
	}
	/**
	 * 得到一个文本回复信息
	 * */
	@RequestMapping(value="news")
	@ResponseBody
	public List<Wxsendmsg> news(HttpServletRequest request, HttpServletResponse response){
		List list = new ArrayList();
		try {
			Wxsendmsg msg = wxsendmsgService.findByid(getParameter("id"));
			if(msg==null)
				return null;
			WxsendmsgDto dto = new WxsendmsgDto();
			dto.setPid(msg.getId());
			dto.setRtype(WeiXinConstant.WEIXIN_MSGTYPE_NEWS);
			List<Map<String, Object>> childs = wxsendmsgService.findNewsMapByDto(dto);
			//是否是多图文
			if(CollectionUtils.isEmpty(childs)){
				list = new ArrayList<Wxsendmsg>();
				list.add(msg);
				return list;
			}
			list.add(msg);
			for(Map<String, Object> child : childs)
				list.add(child);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return null;
	}
}
